import { Injectable } from '@nestjs/common';
import { BaseService } from '@/core/base.service';
import { ClockIn } from '@prisma/client';
import dayjs from 'dayjs';

@Injectable()
export class ClockinService extends BaseService {
  constructor() {
    super();
  }

  async index(uuid: string, uid: number, code: string, isReal: boolean) {
    const res = await this.prisma.$queryRawUnsafe<ClockIn[]>(
      `
      SELECT c.uuid,g.title,g.image,c.date,c.desc FROM clockin AS c
      LEFT JOIN asset AS g ON g.id=c.reward_id
      WHERE c.uuid='${uuid}'
      ORDER BY c.date ASC
      `,
    );

    const list = [];
    let iTotalClockin = 0;
    for (const item of res) {
      let is_clockin = 0;

      const oTodayClockin = await this.prisma.userClockIn.findFirst({
        where: {
          uid,
          uuid,
          date: item.date,
        },
      });

      if (oTodayClockin) {
        is_clockin = 1;
        iTotalClockin++;
      }

      list.push({
        id: item.id,
        uuid: item.uuid,
        reward_type: item.reward_type,
        reward_id: item.reward_id,
        date: dayjs(item.date).toDate(),
        desc: item.desc,
        is_clockin: is_clockin,
      });
    }

    // 积分计算：自己签到1天得100，邀请1个用户签到得50
    let score = iTotalClockin * 100;

    const inviteClock = await this.prisma.$queryRawUnsafe<ClockIn[]>(
      `
      SELECT
        uc.uid,
        count( uc.id ) AS count 
      FROM
        userclockin AS uc
        LEFT JOIN USER AS u ON u.id = uc.uid 
      WHERE
        u.bindCode = '${code}' 
      and u.isReal = 1
      GROUP BY
        uc.uid
      `,
    );

    if (inviteClock) {
      score += inviteClock.length * 50;
    }

    if (!isReal) {
      score = 0;
    }
    return {
      score,
      // uid,
      list: list,
      total_clockin: iTotalClockin,
    };
  }

  async create(uuid: string, uid: number) {
    try {
      await this.prisma.userClockIn.create({
        data: {
          uid,
          uuid,
          date: dayjs().add(8, 'hour').toDate(),
          createdAt: dayjs().add(8, 'hour').toDate(),
        },
      });
    } catch (e) {}
    return true;
  }
}
